package com.febs.security.filter;

import com.febs.common.domain.ResponseBo;
import com.febs.common.enums.CodeMsgEnum;
import com.febs.security.helper.FebsJwtTokenHelper;
import com.febs.security.properties.FebsSecurityProperties;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2021/6/21
 */
@SuppressWarnings("NullableProblems")
@Component
public class FebsTokenFilter extends OncePerRequestFilter {

    @Resource
    private FebsSecurityProperties properties;
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private FebsJwtTokenHelper febsJwtTokenHelper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 尝试获取请求头的 token
        String authToken = request.getHeader(getTokenHeader());
        // 尝试拿 token 中的 username; 若是没有 token 或者拿 username 时出现异常，那么 username 为 null
        String username = this.febsJwtTokenHelper.getUsernameFromToken(authToken);

        // 如果上面解析 token 成功并且拿到了 username 并且本次会话的权限还未被写入
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 用 UserDetailsService 从数据库中拿到用户的 UserDetails 类
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            // 检查用户带来的 token 是否有效; 1.包括 token 和 userDetails 中用户名是否一样， token 是否过期， token 生成时间是否在最后一次密码修改时间之前
            if (this.febsJwtTokenHelper.validateToken(authToken, userDetails)) {
                // 生成通过认证
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // 将权限写入本次会话
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
            if (!userDetails.isEnabled()) {
                ResponseBo.writer(CodeMsgEnum.ACCOUNT_FREEZE.getCode(), CodeMsgEnum.ACCOUNT_FREEZE.getMessage());
                return;
            }
        }
        chain.doFilter(request, response);
    }

    public String getTokenHeader() {
        return this.properties.getToken().getHeader();
    }

}
